package handler

import (
	"encoding/json"
	"novel-shelf/cache"
	"novel-shelf/models"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "6"))
	offset := (page - 1) * size
	var article []models.Article
	redis_key := "list_page" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}
	var total int64
	models.DB.Model(&article).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "msg",
		"data":  article,
		"total": total,
	})
}
